from flask import Flask, render_template, request, redirect, url_for, session, flash
import pymysql
from pymysql.cursors import DictCursor
from werkzeug.security import generate_password_hash, check_password_hash
import os
from db import get_db_connection, init_db
init_db()

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your-secret-key-here')


# 路由
@app.route('/')
def index():
    posts = []
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute('''
                SELECT posts.*, users.username 
                FROM posts 
                JOIN users ON posts.user_id = users.id
            ''')
            posts = cursor.fetchall()
    except Exception as e:
        flash(f"获取帖子失败: {e}")
    finally:
        if conn:
            conn.close()

    return render_template('index.html', posts=posts)


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        try:
            conn = get_db_connection()
            with conn.cursor() as cursor:
                # 检查用户名是否已存在
                cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
                if cursor.fetchone():
                    flash('用户名已存在')
                    return redirect(url_for('register'))

                # 创建新用户
                password_hash = generate_password_hash(password)
                cursor.execute(
                    'INSERT INTO users (username, password_hash) VALUES (%s, %s)',
                    (username, password_hash)
                )
            conn.commit()
            flash('注册成功，请登录')
            return redirect(url_for('login'))
        except Exception as e:
            flash(f"注册失败: {e}")
        finally:
            if conn:
                conn.close()

    return render_template('register.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        try:
            conn = get_db_connection()
            with conn.cursor() as cursor:
                cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
                user = cursor.fetchone()

                if user and check_password_hash(user['password_hash'], password):
                    session['user_id'] = user['id']
                    flash('登录成功')
                    return redirect(url_for('index'))
                else:
                    flash('用户名或密码错误')
        except Exception as e:
            flash(f"登录失败: {e}")
        finally:
            if conn:
                conn.close()

    return render_template('login.html')


@app.route('/logout')
def logout():
    session.pop('user_id', None)
    flash('已退出登录')
    return redirect(url_for('index'))


@app.route('/post/new', methods=['GET', 'POST'])
def new_post():
    if 'user_id' not in session:
        flash('请先登录')
        return redirect(url_for('login'))

    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        user_id = session['user_id']

        try:
            conn = get_db_connection()
            with conn.cursor() as cursor:
                cursor.execute(
                    'INSERT INTO posts (title, content, user_id) VALUES (%s, %s, %s)',
                    (title, content, user_id)
                )
            conn.commit()
            flash('帖子发布成功')
            return redirect(url_for('index'))
        except Exception as e:
            flash(f"发布失败: {e}")
        finally:
            if conn:
                conn.close()

    return render_template('new_post.html')


@app.route('/post/<int:post_id>/edit', methods=['GET', 'POST'])
def edit_post(post_id):
    post = None

    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute('SELECT * FROM posts WHERE id = %s', (post_id,))
            post = cursor.fetchone()

            if not post:
                flash('帖子不存在')
                return redirect(url_for('index'))

            if 'user_id' not in session or post['user_id'] != session['user_id']:
                flash('权限不足')
                return redirect(url_for('index'))

            if request.method == 'POST':
                title = request.form['title']
                content = request.form['content']

                cursor.execute(
                    'UPDATE posts SET title = %s, content = %s WHERE id = %s',
                    (title, content, post_id)
                )
                conn.commit()
                flash('帖子已更新')
                return redirect(url_for('index'))
    except Exception as e:
        flash(f"操作失败: {e}")
    finally:
        if conn:
            conn.close()

    return render_template('edit_post.html', post=post)


@app.route('/post/<int:post_id>/delete', methods=['POST'])
def delete_post(post_id):
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute('SELECT * FROM posts WHERE id = %s', (post_id,))
            post = cursor.fetchone()

            if not post:
                flash('帖子不存在')
                return redirect(url_for('index'))

            if 'user_id' not in session or post['user_id'] != session['user_id']:
                flash('权限不足')
                return redirect(url_for('index'))

            cursor.execute('DELETE FROM posts WHERE id = %s', (post_id,))
            conn.commit()
            flash('帖子已删除')
    except Exception as e:
        flash(f"删除失败: {e}")
    finally:
        if conn:
            conn.close()

    return redirect(url_for('index'))

if __name__ == '__main__':
    init_db()
    app.run(debug=True)